/**
 * 公共请求方封装
 * 以uniapp为例子
 */
import { toLoginPage, CacheUtils, mergeObject, } from "./index.js";
import { consoleErrorWithDate, } from "./log";

const encodeUrlwithArgs = (url, ...args)=>{
    let resultUrl = String(url);
    for(let i=0;i<args.length;i+=2){
		// 因为代理地址包含了？号，所以直接追加&即可
        resultUrl = false ? resultUrl+`?${args[i]}=${args[i+1]}`: resultUrl+`&${args[i]}=${args[i+1]}`;
    }
    return resultUrl;
}

export const encodeUrlWithObj = (url,obj={})=>{
    let arr = [];
    for(let [key, val ] of Object.entries(obj)){
        arr.push(key);
        arr.push(val);
    }
    return encodeUrlwithArgs(url, ...arr);
}

// 默认配置项
const defaultConfig = {
    loading: false, // 默认不需要loading加载款
	needLogin: true, // 默认需要登录
}

// 默认请求配置
const getDefultReqConfig = () => ({
	url: '',
	method: 'POST',
	header: {		
		// ... 默认请求头
	},
	data: {
		lang: uni.getLocale().startsWith('zh')?'zh':'en', // 语言为英语
	},
	config: defaultConfig,
	onSuccess: (data) => data,
	onFail: (err) => err,
	onCompelete: () => {},
})

// 过滤一般请求，这里用code=200代表后端请求正常
const commonResponseFilter = (resultData) => {
	return resultData;
}

const getHanledUrl = (url)=>{
	// #ifdef H5
		return '/server/'+url
	// #endif
	
	return import.meta.env.VITE_SERVER_HOST + String(url).trim()
}

const getLoadingText = ()=>{
	if(uni.getLocale()=='zh-Hans'){
		return '加载中...'
	}
	if(uni.getLocale()=='zh-Hant'){
		return '加载中...'
	}
	// 默认为英语
	return 'loading...';
}

export default async function request(reqConfig) {
	const req = mergeObject(getDefultReqConfig(), reqConfig);
	if (!req.url) {
		return Promise.reject('请求的url不得为空');
	}

	if (req.config?.loading) {
		uni.showLoading({
			title: getLoadingText()
		});
	}

	if(req.config.needLogin&&!CacheUtils.get('userid')){
		req.config?.loading && uni.hideLoading();
		return toLoginPage();
	}
		
	if(String(req.method).toUpperCase()=='GET'||String(req.method).toUpperCase()=='DELETE'){
		req.url = encodeUrlWithObj(req.url, {
			"userid": CacheUtils.get('userid'),
			...req.data,
		});
		req.data = {};
	}else{
		req.data = Object.assign({
			userid: CacheUtils.get('userid'),
		}, req.data);
	}
		

	return new Promise((resolve, reject) => {
		uni.request({
			url: getHanledUrl(req.url),
			method: req.method,
			header: req.header,
			data: req.data,
			success(res) {
				const data = commonResponseFilter(res.data);
				resolve(req.onSuccess ? req.onSuccess(data) : data);
			},
			fail(err) {
				const reasonError = new Error(`接口${req.url} 异常：` + err.errMsg);
				consoleErrorWithDate(err);
				reject(req.onFail ? req.onFail(reasonError) : reasonError);
			},
			complete() {
				req.config?.loading && uni.hideLoading();
				req.onCompelete && req.onCompelete();
			},
		})
	});
}

export const get = (url, data={}, config=defaultConfig) => request({
	url: url,
	data: data,
	method: 'GET',
	config: config,
});

export const post = (url, data={}, config=defaultConfig) => request({
	url: url,
	data: data,
	method: 'POST',
	config: config,
});